package com.cms.controllers.admin;


import com.cms.common.config.UploadConfig;
import com.cms.common.model.entity.UploadFile;
import com.cms.common.model.services.UploadFileService;
import com.cms.common.model.vo.ResponseResult;
import com.cms.common.utils.FileMd5Utils;
import com.cms.common.utils.ImageUploadUtil;
import com.cms.common.utils.PictureUtil;
import com.cms.controllers.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;


@RestController("file")
@RequestMapping("/api/file")
public class FileController extends BaseController {


    @Autowired
    UploadFileService uploadFileService;


    @GetMapping("/{md5}")
    public void file(@PathVariable("md5") String md5) throws IOException {
        UploadFile uploadFile = uploadFileService.findByMd5(md5);
        if (uploadFile == null) {
            return;
        }
        File file = new File(UploadConfig.uploadPath + "/" + uploadFile.getPath() + "/" + uploadFile.getName());
        if (!(file.exists() && file.canRead())) {//返回默认图片
            file = new File(request.getSession().getServletContext().getRealPath("/")
                    + "resource/icons/auth/root.png");
        }
        FileInputStream inputStream = new FileInputStream(file);
        byte[] data = new byte[(int) file.length()];
        inputStream.read(data);
        if (uploadFile.getType().equals("img")) {
            response.setContentType("image/png");
        }

        OutputStream stream = response.getOutputStream();
        stream.write(data);
        stream.flush();
        stream.close();
        inputStream.close();
    }

    @GetMapping("/{md5}/thumb/{width}/{height}")
    public void file(@PathVariable("md5") String md5, @PathVariable("width") int width, @PathVariable("height") int height) throws IOException {
        UploadFile uploadFile = uploadFileService.findByMd5(md5);
        if (uploadFile == null) {
            return;
        }
        File file = new File(UploadConfig.uploadPath + "/" + uploadFile.getPath() + "/" + width + "_" + height + "_" + uploadFile.getName());
        if (!file.exists()) {//缩略图不存在
            File file2 = new File(UploadConfig.uploadPath + "/" + uploadFile.getPath() + "/" + uploadFile.getName());
            if (file2.exists()) {
                PictureUtil.photoSmaller(file2, file, width, height);
            }
        }

        if (!(file.exists() && file.canRead())) {//返回默认图片
            file = new File(request.getSession().getServletContext().getRealPath("/")
                    + "resource/icons/auth/root.png");
        }
        FileInputStream inputStream = new FileInputStream(file);
        byte[] data = new byte[(int) file.length()];
        inputStream.read(data);
        if (uploadFile.getType().equals("img")) {
            response.setContentType("image/png");
        }

        OutputStream stream = response.getOutputStream();
        stream.write(data);
        stream.flush();
        stream.close();
        inputStream.close();
    }


    @PostMapping("/upload")
    public ResponseResult imageUpload(HttpServletRequest request,
                                      HttpServletResponse response) {

        //String DirectoryName = "D:/test/";
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            String path = simpleDateFormat.format(new Date());
            String filePath = UploadConfig.uploadPath + "/" + path;
            String fileName = ImageUploadUtil.ckeditor(request, response, filePath);
            if (fileName.isEmpty()) {
                return ResponseResult.fail("上传失败");
            }
            String md5 = FileMd5Utils.getFileMD5String(filePath + "/" + fileName);
            UploadFile uploadFile = uploadFileService.findByMd5(md5);
            if (uploadFile == null) {
                String ext = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
                uploadFile = new UploadFile();
                uploadFile.setName(fileName);
                uploadFile.setExt(ext);
                uploadFile.setMd5(md5);
                uploadFile.setPath(path);
            } else {
                new File(filePath + "/" + fileName).delete();//删除这个文件，使用旧文件
            }
            uploadFile.setPointCount(uploadFile.getPointCount() + 1);
            uploadFile = uploadFileService.save(uploadFile);
            return ResponseResult.success(uploadFile);
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return ResponseResult.fail(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.fail(e.getMessage());
        }
    }
}
